#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <mysql/mysql.h>

int add(MYSQL *mysql) {
    char* sql = "insert into test_tb values (null, 18, '小李',  80.5);";
    int ret = mysql_query(mysql, sql);
    if(ret != 0) {
        printf("query sql failed:%s\n", mysql_error(mysql));
        return -1;
    }
    return 0;
}
int mod(MYSQL *mysql) {
    char* sql = "update test_tb set name='小王' where id=2;";
    int ret = mysql_query(mysql, sql);
    if(ret != 0) {
        printf("query sql failed:%s\n", mysql_error(mysql));
        return -1;
    }
    return 0;
}
int del(MYSQL *mysql) {
    char* sql = "delete from test_tb where id=2;";
    int ret = mysql_query(mysql, sql);
    if(ret != 0) {
        printf("query sql failed:%s\n", mysql_error(mysql));
        return -1;
    }
    return 0;
}
int get(MYSQL *mysql) {
    char* sql = "select * from test_tb where id=1;";
    int ret = mysql_query(mysql, sql);
    if(ret != 0) {
        printf("query sql failed:%s\n", mysql_error(mysql));
        return -1;
    }
    MYSQL_RES *res = mysql_store_result(mysql);
    if(res == NULL) {
        printf("store result failed:%s\n", mysql_error(mysql));
        return -1;
    }
    int row_num = mysql_num_rows(res);
    int col_num = mysql_num_fields(res);
    for(int i = 0; i < row_num; i++) {
        MYSQL_ROW row = mysql_fetch_row(res);
        for(int j = 0; j < col_num; j++) {
            printf("%s\t", row[j]);
        }
        printf("\n");
    }
    mysql_free_result(res);
    return 0;
}
int main()
{
    //初始化操作句柄
    MYSQL *mysql = mysql_init(NULL);
    //连接mysql服务器
    if(mysql_real_connect(mysql, "127.0.0.1", "root", "123456", "test_db", 0, NULL, 0) == NULL) {
        printf("connect mysql server failed!\n");
        return -1;
    }
    //设置客户端字符集
    mysql_set_character_set(mysql, "utf8");
    //add(mysql);
    //mod(mysql);
    //del(mysql);
    get(mysql);
    mysql_close(mysql);
    return 0;
}